package com.heima.wemadia.interceptor;

import com.alibaba.fastjson.JSON;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.wemedia.entity.WmUser;
import com.heima.wemadia.utils.WmThreadLocalUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class WmTokenInterceptor extends HandlerInterceptorAdapter {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String userId = request.getHeader("userId");
        if(StringUtils.isBlank(userId)){
            response.setStatus(401);
            ResponseResult responseResult = ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
            response.setContentType("application/json;charset=utf-8");
            response.getWriter().write(JSON.toJSONString(responseResult));
            return false;
        }
        WmUser wmUser=new WmUser();
        wmUser.setId(Long.valueOf(userId));
        WmThreadLocalUtil.setUser(wmUser);
        return super.preHandle(request, response, handler);
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

        WmThreadLocalUtil.clear();
        super.postHandle(request, response, handler, modelAndView);
    }
}
